#include "head.h"
int my_pipe[2];

// 信号函数
void exit_func(int num){
    write(my_pipe[0],"exit",4);
}

int main(int args, char *argv[]){
    // 检错标记位
    int ret;
    // 创建父子进程
    ret = pipe(my_pipe);
    ERROR_CHECK(ret,-1,"pipe");
    // 父子进程分流
    if (fork() != 0){
        // 关闭管道读端
        close(my_pipe[0]);
        // 父进程注册信号
        void *pret = (void *)signal(SIGINT,exit_func);
        ERROR_CHECK(pret,NULL,"signal");
        // 等待子进程退出
        wait(NULL);
        // 关闭滚到写端
        close(my_pipe[1]);
    }
    // 子进程程脱离前台进程组
    ret = setpgid(0,0);
    ERROR_CHECK(ret,-1,"setpgid");
    // 子进程的主线程关闭管道写端
    close(my_pipe[1]);
    // 子进程初始化子线程
    pool_t pool;
    ret = thread_init(&pool);
    ERROR_CHECK(ret,-1,"thread_init");
    // 初始化网络连接
    int socket_fd;
    socket_init(&socket_fd);
    // 初始化epoll监听
    int epoll_fd = epoll_create(1);
    ERROR_CHECK(epoll_fd,-1,"epoll_create");
    // 添加epoll监听
    ret = epoll_add_fd(epoll_fd,socket_fd);
    ERROR_CHECK(ret,-1,"epoll_add_fd");
    ret = epoll_add_fd(epoll_fd,my_pipe[0]);
    ERROR_CHECK(ret,-1,"epoll_add_fd");
    // 初始化mysql数据库连接
    MYSQL mysql;
    ret = mysql_real_init(&mysql);
    ERROR_CHECK(ret,-1,"mysql_init");
    // 初始化协议头部
    train_t t;
    // 开始监听
    while(1){
        struct epoll_event events[10];
        int ready_nums = epoll_wait(epoll_fd,events,ARR_LEN(events),-1);
        for (int i = 0; i < ready_nums; i++){
            int fd = events[i].data.fd;
            if (fd == socket_fd){
                int net_fd = accept(socket_fd,NULL,NULL);
                ERROR_CHECK(ret,-1,"accept");
                ret = is_login_or_register(net_fd, &t, &mysql);
                if (ret == 0){

                }
                if (ret == -1){

                }
            }
            if (fd == my_pipe[0]){

            }
        }
    }
}
